package org.lanqiao.dao;


import org.lanqiao.entity.OrderInfo;
import org.lanqiao.mapper.UserMapper;
import org.lanqiao.mapper.WxuserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Random;

@Repository
public class AliPayDao {
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    RedisTemplate redisTemplate;
    public String getOrderId(String userId, String money) {
        ///生成订单号
        String orderId;
        orderId = getOrderIdByTime();
        //保存订单信息（OrderInfo） 到redis 中
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setTotalAmount(money);
        orderInfo.setOutTradeNo(orderId);
        orderInfo.setSubject("余额充值");
        orderInfo.setBody("礼物充值");
        orderInfo.setTimeoutExpress("5m");
        orderInfo.setProductCode("RENCHUNXU");
        //将对象存入redis中
        redisTemplate.opsForValue().set(orderId,orderInfo);
        //返回订单id
        return orderId;
    }

    public OrderInfo getPayInfoByOrderId(String orderId) {
        //从redis 中查询订单信息
        OrderInfo o = (OrderInfo)redisTemplate.opsForValue().get(orderId);
        return o;
    }

    public void recharge(String orderId) {
        //当前时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        //充值
        OrderInfo o = (OrderInfo)redisTemplate.opsForValue().get(orderId);
        String wxId = o.getUserId();
        String totalAmount = o.getTotalAmount();
        wxuserMapper.charge(new BigDecimal(totalAmount) ,wxId);
        //充值记录
        wxuserMapper.addRechargeRecord(orderId,new BigDecimal(o.getTotalAmount()),timestamp,1,o.getUserId());
        //删除redis(占用空间)
        redisTemplate.delete(orderId);
    }
    //自动生成订单号=时间+随机数
    public static String getOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }

}
